$(function () {
	
	// 保存当前已选择的教师Id
	var teacherIds = [];
	
	// 分页参数条件
	function queryParams() {
		var param = {
	        name : $("#teacherName").val(),
	        type : $("#teacherType").val(),
	        pageNum : this.pageNumber,
	        pageSize : this.pageSize
	    }
	    return param;
	}
	
	// 响应消息处理
	function responseHandler(res) {
		if (res) {
	        return {
	            "rows" : res.rows,
	            "total" : res.total
	        };
	    } else {
	        return {
	            "rows" : [],
	            "total" : 0
	        };
	    }
	}
	
	function operateFormatter(value, row, index) {
        return [
            '<a class="select" href="javascript:void(0)" title="选择">',
            '<i class="glyphicon glyphicon-check">选择</i>',
            '</a>  '
        ].join('');
    }

	// 删除已选择的教师
	function delTeacher() {
		var id = $(this).attr("data-id");
    	
    	// 找出id，并删除
    	for (index in teacherIds) {
    		if (id == teacherIds[index]) {
    			teacherIds.splice(index, 1);
    			break;
    		}
    	}
    	
    	$(this).closest("tr").remove();
	}
	
	// 模态框事件处理
    var operateEvents = {
        'click .select': function (e, value, row, index) {
        	
        	// 校验该教师是否已被选择
        	for (index in teacherIds) {
        		if (row.id == teacherIds[index]) {
        			$(e.delegateTarget).popover({
        				content : "该教师已被选择",
        				trigger : "manual",
        				placement : "top"
        			});
        			$(e.delegateTarget).popover("show");
        			
        			// 清除提示框
        			setTimeout(function () {
        				$(e.delegateTarget).popover("destroy");
        			}, 5000);
        			return;
        		}
        	}
        	
        	teacherIds.push(row.id);
        	var teacherType = $("#teacherType").val();
        	
        	var tr = $([
    			"<tr>",
    			"<td>" + row.id + "</td>",
    			"<td>" + row.name + "</td>",
    			"<input type='hidden' name='teacherIds' value='" + row.id + "'>",
    			"</tr>"
    		].join(""));
    		var td = $(
    			"<td><button data-type='del' data-id='" + row.id + "' type='button' class='btn-xs btn-link'>删除</button></td>"
    		);
    		td.find("button").click(delTeacher);
    		tr.append(td);
    		$("button[data-teacher-type='" + teacherType + "']").closest("tr").before(tr);
            
            $("#teacherSelect").modal("hide");
        }
    };
	
    // 删除教师按钮事件
    $("button[data-type='del']").click(delTeacher);
    
    // 模态框的搜索按钮
    $("button.selectTeacher").click(function () {
		$("#teacherForm").bootstrapTable("refresh");
	});
    
    // 初始化模态框的表格
	$("#teacherForm").bootstrapTable({
		method:'GET',
		dataType:'json',
		contentType:"application/json",
		cache: false,
        striped: true,					// 是否显示行间隔色
        sidePagination: "server",		// 服务端分页
        url:"teacher/lists",
        pagination:true,
        queryParams : queryParams,
        pageNumber:1,					// 初始化加载第一页，默认第一页
        pageSize: 10,					// 每页的记录行数（*）
        pageList: [10, 25, 50, 100],	// 可供选择的每页的行数（*）
        showExport: false,
        responseHandler: responseHandler,
        columns: [
        	{
        		field: "id",
        		title: "教师编号",
        		align: "center",
        		valign: "middle"
        	},
        	{
        		field: "name",
        		title: "教师名称",
        		align : "center",
                valign : "middle"
        	},
        	{
        		field: "remarks",
        		title: "备注",
        		align : "center",
                valign : "middle"
        	},
        	{
        		title: "操作",
        		align : "center",
                valign : "middle",
                events: operateEvents,
                formatter: operateFormatter
        	}
        ]
	});
	
	// 初始化日期控件
	$(".date").datetimepicker({
	    format: 'yyyy-mm-dd',
	    autoclose: true,
	    clearBtn: true,
	    minView: 2,
	    language: "zh-CN"
	});
	
	// 获取教师类型的筛选条件
	$("button[data-type='add']").click(function () {
		$("#teacherType").val($(this).attr("data-teacher-type"));
		$("#teacherForm").bootstrapTable("refresh");
	});
	
	// 重置时把教师列表也给重置掉
	$("button[type='reset']").click(function () {
		$("button[data-teacher-type]").parents("tr").each(function (index) {
			$(this).siblings().remove();
		});
		teacherIds = [];
	});
	
	// 清除提示框
	$("button[data-dismiss='modal']").click(function () {
		$("#teacherForm a.select").popover("destroy");
	});
	
	// 参数校验
	$("#class-form").validate({
		errorElement : "label",  
        errorClass : "text-danger",  
        rules : {
        	name : {
            	required : true,
            	minlength: 2,
            	maxlength: 50
            },
            "product.id": {
                required : true,
                digits : true
            },  
            preparatoryDate : {  
            	dateISO:true
            },  
            openDate : {
            	dateISO:true
            },  
            trainDate : {
            	dateISO:true
            },  
            endDate : {
            	dateISO:true
            },  
            remarks: {  
            	maxlength: 500
            }
        },
        submitHandler : function (validator, form) {
        	if (0 == teacherIds.length) {
        		$("#error").modal('show');
        		return ;
        	}
        	validator.submit();
        }
	});
});